import axios from './axios'

export function getweixinCode () {
  const appid = 'wx716991b519d93142'
  let local = window.location.href
  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
}

export async function wxcallback(func){
  let code = getUrlCode().code;
  if(code){
    await axios.post('/wxcallback', code).then(res => {
      if (res.state == '200') {
        const token = res.data.token
        const userInfo = res.data.user
        localStorage.setItem('accessToken', token.accessToken)
        localStorage.setItem('refreshToken', token.refreshToken)
        localStorage.setItem('openId', userInfo.openId)
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        func && func()
      }
    })
    //去除返回url中的code
    let url = window.location.href
    let domain = url.split("?")[0] + '#' + url.split("#")[1]
    window.location.href = domain
  }
}

export function getUrlCode() {
  // 截取url中的code方法
  let url = location.search;
  let theRequest = new Object();
  if (url.indexOf("?") != -1) {
    let str = url.substr(1);
    let strs = str.split("&");
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
    }
  }
  // console.log(theRequest);
  return theRequest;
}
